/**************************************************************************************************

	NSurvey - The web survey and form engine
	Copyright (c) 2004, Thomas Zumbrunn. (http://www.nsurvey.org)

	Dotnetnuke PA module 
	Copyright (c) 2004, Oliver Hine (oliver.hine@gmail.com)

	This program is free software; you can redistribute it and/or
	modify it under the terms of the GNU General Public License
	as published by the Free Software Foundation; either version 2
	of the License, or (at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program; if not, write to the Free Software
	Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

************************************************************************************************/

using Microsoft.VisualBasic;
using System;
using System.Resources;
using System.Reflection;
using System.Web.UI;
using System.Text.RegularExpressions;
using System.Web.UI.WebControls;
using Votations.NSurvey.DataAccess;
using Votations.NSurvey.Data;
using Votations.NSurvey.WebAdmin.UserControls;
using Votations.NSurvey.Web;
using Votations.NSurvey.BusinessRules;
using Votations.NSurvey.Web.Security;
using Votations.NSurvey.UserProvider;

namespace Votations.NSurvey.WebAdmin
{

	public class PageBase : DotNetNuke.Entities.Modules.PortalModuleBase
	{
		public PageBase()
		{
			if (Context != null)
			{
				// Creates new nsurvey context
				// from the current user name
				NSurveyContext.Current.User = 
					UserFactory.Create().CreatePrincipal(Helpers.WebHelper.CurrentContext.User.Identity.Name);
			}
		}

		public int SurveyId
		{
			get 
			{ 
				if (_surveyId == -1)
				{
					ValidateSurveyId();
				
					if (_surveyId == -1 )
					{
						if (CheckRight(NSurveyRights.CreateSurvey, false))
						{
							//Response.Write(string.Format("<a href=\"{0}\">{1}</a>", UINavigator.CreateSurveyLink.Substring(1,UINavigator.CreateSurveyLink.Length-1), GetPageResource("NoSurveysAvailableMessage")));
						}
						else
						{
							if (NSurveyUser.Identity.UserId == -1)
							{
								Response.Write(GetPageResource("NoAnonymousRightsMessage"));
							}
							else
							{
								Response.Write(GetPageResource("NoSurveysAndNoRightMessage"));

							}
							Response.End();
						}
						
					}
				}
	
				return _surveyId; 
			}
			set { _surveyId = value; }
		}
		
		public INSurveyPrincipal NSurveyUser
		{
			get { return NSurveyContext.Current.User; }
		}

		public string CurrentFolder(string file)
		{
			return this.ResolveUrl("~/DesktopModules/nSurvey/") + file;
		}

		public void CreateLinks()
		{
		}

		public int MenuIndex
		{
			get 
			{
				return Request["menuindex"]!=null && Information.IsNumeric(Request["menuindex"]) ? 
					Convert.ToInt32(Request["menuindex"]) : -1;
			}
		}

		public string GetPageResource(string resourceName)
		{
			return _resourceManagerInstance.GetString(resourceName);
		}

		void ValidateSurveyId()
		{
			if (NSurveyUser.Identity.IsAdmin || 
				NSurveyUser.Identity.HasAllSurveyAccess)
			{
				_surveyId = Information.IsNumeric(Request["SurveyID"]) && int.Parse(Request["SurveyID"]) != -1 ?
					int.Parse(Request["SurveyID"]) : new Surveys().GetFirstSurveyId();
			}
			else
			{
				_surveyId = Information.IsNumeric(Request["SurveyID"]) && int.Parse(Request["SurveyID"]) != -1 ?
					int.Parse(Request["SurveyID"]) : new Surveys().GetFirstSurveyId(NSurveyUser.Identity.UserId);

				// Makes sure the user is the owner of the survey
				if (Information.IsNumeric(Request["SurveyID"]) && _surveyId != -1 && 
					!new Survey().CheckSurveyUser(_surveyId, NSurveyUser.Identity.UserId))
				{
					_surveyId = new Surveys().GetFirstSurveyId(NSurveyUser.Identity.UserId);
				}

			}

		}


		/// <summary>
		/// Look up the give item texts in the resource file 
		/// to translate them
		/// </summary>
		/// <param name="dropDown"></param>
		public void TranslateListControl(ListControl unTranslatedListControl)
		{
			string translatedText;
			foreach (ListItem item in unTranslatedListControl.Items)
			{
				translatedText = GetPageResource(item.Text);
				item.Text = translatedText == null ? item.Text : translatedText;
			}
		}

		public bool isEmail(string inputEmail)
		{
			string strRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
				@"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" + 
				@".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
			Regex re = new Regex(strRegex);
			if (re.IsMatch(inputEmail))
				return (true);
			else
				return (false);
		}

		/// <summary>
		/// Check if the current user has the given right
		/// else if specified redirect to the access denied page
		/// </summary>
		public bool CheckRight(NSurveyRights right, bool accessDeniedRedirect)
		{
			if (NSurveyUser.Identity.IsAdmin || 
				NSurveyUser.HasRight(right))
			{
				return true;
			}
			else if (accessDeniedRedirect)
			{
				UINavigator.NavigateToAccessDenied(SurveyId, MenuIndex);
			}

			return false;
		}

		// Check if the system was setup in single user mode
		public bool IsSingleUserMode(bool redirectIfSingle)
		{
			// Did the system setup a dummy admin
			if (NSurveyUser.Identity.UserId == 0 &&
				NSurveyUser.Identity.IsAdmin)
			{
				if (redirectIfSingle)
				{
					UINavigator.NavigateToAccessDenied(SurveyId, MenuIndex);
				}
				return true;
			}
			return false;
		}

		System.Resources.ResourceManager _resourceManagerInstance = 
			new System.Resources.ResourceManager("Votations.NSurvey.WebAdmin.Resources.NSurveyAdmin",
			System.Reflection.Assembly.GetExecutingAssembly());

		private int _surveyId = -1;
	}
}
